package org.daidai.abstrusewriting.homepage.classify.client;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2016/10/31.
 */

public class OkHttpUtilImpl extends AbstractHttpUtil{
    private final OkHttpClient mOkHttpClient;

    public OkHttpUtilImpl() {
        this.mOkHttpClient = new OkHttpClient();
    }


    @Override
    public byte[] doGetData(String url) {
        byte[] ret=null;
        if (url != null) {
            Request.Builder builder = new Request.Builder();
            builder.url(url)
                    .get();
            Request request = builder.build();

            try {
                Response response = mOkHttpClient.newCall(request).execute();
                ResponseBody body = response.body();
                ret = body.bytes();
                response.close();
                response=null;


            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return ret;
    }

    @Override
    public void doGetDataAsync(String url, final HttpCallback callback) {
        if (url != null) {
            Request.Builder builder = new Request.Builder();
            builder.url(url)
                    .get();
            Request request = builder.build();

            mOkHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    int code = response.code();
                    byte[] data = response.body().bytes();
                    HttpUrl httpUrl = call.request().url();

                    if (callback != null) {
                        callback.onSuccess(httpUrl.toString(),code,data);
                    }

                }
            });
        }

    }
}
